﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;
using umbraco;

namespace AttackMonkey.TabHider
{
	class Config
	{
		// Fields
		private static Config _instance;
		private Dictionary<string, List<ConfigItem>> _configEntries;
		private bool _onlyShowToRoot;

		public bool OnlyShowToRoot
		{
			get { return _onlyShowToRoot; }
		}

		// Methods
		private Config()
		{
			this.ConfigEntries = new Dictionary<string, List<ConfigItem>>();
			this.LoadXmlConfig();
		}

		private void LoadXmlConfig()
		{
			XmlDocument document = new XmlDocument();
			document.Load(HttpContext.Current.Server.MapPath("~/config/tabHider.config"));
			
			//set whether to only to ignore all rules for Root instead of all Administrators
			XmlNode temp = document.SelectSingleNode("/tabHider/onlyShowToRoot");
			_onlyShowToRoot = false;
			if (temp != null)
			{
				if (!string.IsNullOrEmpty(temp.InnerText))
				{
					_onlyShowToRoot = Convert.ToBoolean(temp.InnerText);
				}
			}

			//set whether to hide hidden validators
			DisableHiddenValidators = true;

			if (!string.IsNullOrEmpty(document.SelectSingleNode("/tabHider/disableHiddenValidators").InnerText))
			{
				if (document.SelectSingleNode("/tabHider/disableHiddenValidators").InnerText.ToLower() == "false")
				{
					DisableHiddenValidators = false;
				}
			}
			
			//load in tab configurations
			foreach (XmlNode node in document.SelectNodes("/tabHider/hideRules/add"))
			{
				if (node.NodeType == XmlNodeType.Element)
				{
					ConfigItem item = new ConfigItem();
					item.TabName = node.Attributes["tabName"].Value.ToLower();
					item.HideFrom = node.Attributes["hideFrom"].Value.Split(',').Select(o => o.Trim().ToLower());
					if (node.Attributes["docTypeAliases"] != null)
					{
						if (!string.IsNullOrEmpty(node.Attributes["docTypeAliases"].Value))
						{
							item.DocTypeAliases = node.Attributes["docTypeAliases"].Value.Split(',').Select(o => o.Trim().ToLower());
						}
					}

					if (!this.ConfigEntries.ContainsKey(item.TabName))
					{
						this.ConfigEntries.Add(item.TabName, new List<ConfigItem>());
					}
					this.ConfigEntries[item.TabName].Add(item);
				}
			}
		}

		// Properties
		public Dictionary<string, List<ConfigItem>> ConfigEntries
		{
			get
			{
				return _configEntries;
			}
			set
			{
				_configEntries = value;
			}
		}
		
		public bool DisableHiddenValidators { get; set; }

		public static Config Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new Config();
				}
				return _instance;
			}
		}
		
		public static void RefreshInstance()
		{
			_instance = null;
		}
	}
}